import http from '@/utils/http'
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'

type Token = string

export type Infos = {
  name: string
  head: string
  _id: string
  [key: string]: unknown
}

export type UsersState = {
  token: Token
  infos: Infos
}

type Login = {
  email: string
  pass: string
}

const usersSlice = createSlice({
  name: 'users',
  initialState: {
    token: '',
    infos: {},
  } as UsersState,
  reducers: {
    setToken: (state, action: PayloadAction<Token>) => {
      state.token = action.payload
    },
    setInfos: (state, action: PayloadAction<Infos>) => {
      state.infos = action.payload
    },
    clearToken(state) {
      state.token = ''
    },
  },
})

export const loginAction = createAsyncThunk(
  'users/loginAction',
  async (payload: Login) => {
    const res = await http.post('/users/login', payload)
    return res.data
  }
)

export const infosAction = createAsyncThunk('users/infosAction', async () => {
  const res = await http.get('/users/infos')
  return res.data
})

export const { setToken, setInfos, clearToken } = usersSlice.actions

export default usersSlice.reducer
